package com.nsoft.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.simpleframework.xml.core.Persister;

import com.nsoft.ui.R;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;

public class utils {
	private static String externalPath=Constant.EMPTY;
	private static String fullBasePath=Constant.EMPTY;
	private static String bookPath=Constant.EMPTY;
	private static String historyPath=Constant.EMPTY;
	private static String thumbPath=Constant.EMPTY;
	private static String historyListFile=Constant.EMPTY;
	private static String iconPath=Constant.EMPTY;
	
	public static String getExternalStoragePath(){
		return externalPath;
	}
	
	public static String getFullBasePath(){
		if (fullBasePath.equals(Constant.EMPTY)){
			checkTempFolder();
		}
		return fullBasePath;
	}
	
	public static String getBookPath(){
		if (bookPath.equals(Constant.EMPTY)){
			checkTempFolder();
		}
		return bookPath;
	}
	
	public static String getHistoryPath(){
		if (historyPath.equals(Constant.EMPTY)){
			checkTempFolder();
		}
		return historyPath;
	}
	
	public static String getThumbPath(){
		if (thumbPath.equals(Constant.EMPTY)){
			checkTempFolder();
		}
		return thumbPath;
	}
	
	public static String getHistoryListFile(){
		if (historyPath.equals(Constant.EMPTY)){
			checkTempFolder();
		}
		historyListFile=historyPath+'/'+
			Constant.UTIL_BOOKLIST_HISTORY_FILE;
		return historyListFile;
	}
	
	public static String getIconPath(){
		if (iconPath.equals(Constant.EMPTY)){
			checkTempFolder();
		}
		return iconPath;
	}
	
	public static boolean checkTempFolder(){
		if (!fullBasePath.equals(Constant.EMPTY)){
			return true;
		}
		boolean isFolderCreated=false;
		
		externalPath=Environment.
				getExternalStorageDirectory().
				getAbsolutePath()+'/';
		fullBasePath=externalPath+
				Constant.UTIL_SDCARD_BASEFOLDER_NAME;
		File p=new File(fullBasePath);
		if (!p.exists()){
			p.mkdir();
			isFolderCreated=true;
		}
		bookPath=fullBasePath+'/'+
				Constant.UTIL_SDCARD_BOOKFOLDER_NAME;
		p=new File(bookPath);
		if (!p.exists()){
			p.mkdir();
			isFolderCreated=true;
		}
		historyPath=fullBasePath+'/'+
				Constant.UTIL_SDCARD_HISTORYFOLDER_NAME;
		p=new File(historyPath);
		if (!p.exists()){
			p.mkdir();
			isFolderCreated=true;
		}
		thumbPath=historyPath+'/'+
				Constant.UTIL_SDCARD_THUMBFOLDER_NAME;
		p=new File(thumbPath);
		if (!p.exists()){
			p.mkdir();
			isFolderCreated=true;
		}
		iconPath=fullBasePath+'/'+
				Constant.UTIL_SDCARD_ICONFOLDER_NAME;
		p=new File(iconPath);
		if (!p.exists()){
			p.mkdir();
			isFolderCreated=true;
		}
		return !isFolderCreated;
	}
	
	public static boolean encodeXml(Object o,File f) 
							throws Exception {
		Persister persister = new Persister();
		persister.write(o,f);
		return true;
	}
	
	public static Object decodeXml(File f,Class<?> c)
							throws Exception {
		Persister persister = new Persister();
		return persister.read(c,f);
	}
	
	public static void showInfo(
			Context ctx,String title,String msg){
		AlertDialog.Builder alert=
				new AlertDialog.Builder(ctx);
		alert.setIcon(R.drawable.ic_info);
		alert.setTitle(title).
			setMessage(msg).
			setPositiveButton(Constant.DIALOG_OK,
				new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(
							DialogInterface dialog, 
							int which) {
						dialog.cancel();
					}
				}).create().show();
	}
	
	public static void showError(
			Context ctx,String title,String msg){
		AlertDialog.Builder alert=
				new AlertDialog.Builder(ctx);
		alert.setIcon(R.drawable.ic_cancel);
		alert.setTitle(title).
			setMessage(msg).
			setPositiveButton(Constant.DIALOG_OK,
				new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(
							DialogInterface dialog, 
							int which) {
						dialog.cancel();
					}
				}).create().show();
	}
		
    public static View addView(String content,Context ctx){
		WebView wv=new WebView(ctx);
		wv.loadData(content,"text/html","utf-8");
		return wv;
    }
    
    public static void unzipFile(String zipFile,
    		String outputFolder,boolean updateHtml) 
    							throws IOException{
    	byte[] buffer=new byte[1024];
        
    	try{
    		File folder=new File(outputFolder);
	       	if(!folder.exists()){
	       		folder.mkdir();
	       	}
    
	       	ZipInputStream zis=new ZipInputStream(
	       				new FileInputStream(zipFile));
	       	ZipEntry ze=zis.getNextEntry();
	       	String outputFile=Constant.EMPTY;
	       	while(ze!=null){
	       		String fileName=ze.getName();
	       		outputFile=outputFolder+
            			File.separator+fileName;
	       		File newFile=new File(outputFile);
	            new File(newFile.getParent()).mkdirs();
	            FileOutputStream fos=new 
	            		FileOutputStream(newFile);             
	
	            int len;
	            while ((len=zis.read(buffer))>0){
	            	fos.write(buffer,0,len);
	            }
	            fos.close();   
	            
	            if (updateHtml&&outputFile.
	            		endsWith(Constant.UTIL_HTML)){
	            	updateHtml(newFile.getAbsolutePath());
	            }
	            ze=zis.getNextEntry();
	       	}
	       	zis.closeEntry();
	       	zis.close();
   
    	}catch(IOException e){
    		Log.v("utils.unzipFile()",
    			e.getClass()+": "+e.getMessage());
    		throw e;
    	}    	
    }
    
	private static void updateHtml(String htmlFilePath){
		final String CHECKED_KEYWORD=
				Constant.utils.UTIL_ZOOM_METATAG;
		
		if (!htmlFilePath.endsWith(Constant.UTIL_HTML))
			return;
		
		File f=new File(htmlFilePath);
		
        FileInputStream fs=null;
        InputStreamReader in=null;
        BufferedReader br=null;

        StringBuffer sb=new StringBuffer();
        String textinLine;

        try{
        	fs=new FileInputStream(f);
            in=new InputStreamReader(fs);
            br=new BufferedReader(in);

            while(true){
            	textinLine=br.readLine();
                if(textinLine==null)
                    break;
                sb.append(textinLine);
            }
            
            String textToEdit=CHECKED_KEYWORD;
            int offs=sb.indexOf(textToEdit);
            sb.replace(offs,offs+textToEdit.length(),
            		Constant.utils.UTIL_ZOOM_METATAG1);

            fs.close();
            in.close();
            br.close();
        }catch (IOException e){
        	Log.v("utils.updateHtml() - read & modify process",
        		e.getClass()+": "+e.getMessage());
        }

        try{
            FileWriter fstream=new FileWriter(f);
            BufferedWriter outobj=
            		new BufferedWriter(fstream);
            outobj.write(sb.toString());
            outobj.close();
        }catch (IOException e){
        	Log.v("utils.updateHtml() - write out process",
        		e.getClass()+": "+e.getMessage());
        }
	}
	
	/**
     * delete an non-empty folder (recursively)
     * @param file
     * @throws IOException
     */
    public static void delete(File file) 
    			throws IOException{
     	if(file.isDirectory()){
     		if(file.list().length==0){
     			file.delete();
    		}else{
    			String files[]=file.list();
    			for (String temp:files){
    				File fileDelete=new File(file,temp);
    				delete(fileDelete);
    			}

    			if(file.list().length==0){
    				file.delete();
    			}
    		}
     	}else{
    		file.delete();
    	}
    }
}
